package com.xj.api.bussiness.wxLogin.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xj.api.base.web.BaseController;
import com.xj.api.bussiness.userInfo.service.ITbUserInfoService;
import com.xj.api.bussiness.wxLogin.common.GetWxUserInfo;
import com.xj.api.bussiness.wxLogin.service.IWxLoginService;
import com.xj.common.base.common.bean.AbstractBean;
import com.xj.common.bussiness.wxLogin.entity.WxAccessToken;
import com.xj.common.bussiness.wxLogin.entity.WxLoginMould;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * 微信用户登录接口
 */
@RestController
@RequestMapping("/wxUserLog")
public class wxLoginController extends BaseController {

    @Autowired
    private IWxLoginService wxLoginService;

    @GetMapping("/login")
    @ApiOperation(value = "微信用户登录,使用code换取微信openid和session_key,返回openid", httpMethod = "GET", notes = "微信用户登录,使用code换取微信openid和session_key,返回openid")
    public AbstractBean login(WxLoginMould wxLoginMould){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+wxLoginMould.getAppid()+"&secret="+wxLoginMould.getSecret()+"&js_code=" + wxLoginMould.getJs_code() + "&grant_type="+wxLoginMould.getGrant_type();
        HashMap<String, Object> bean = wxLoginService.GET(url);
        if(bean.get("status").toString().equals("OK")){
            //取出openid,和session_key
            String key = bean.get("openid").toString();
            return json(key);
        }
        return error();
    }

    @GetMapping("/getUseuInfo")
    @ApiOperation(value = "  获取微信用户信息", httpMethod = "GET", notes = "  获取微信用户信息")
    public JSONObject getUseuInfo(String encryptedData,String openid,String iv) {
        JSONObject jsonObject = wxLoginService.getUserInfo(encryptedData, openid,iv);
        return jsonObject;
    }

    @GetMapping("/haverWxRegister")
    @ApiOperation(value = "  查询微信用户是否注册", httpMethod = "GET", notes = "  查询微信用户是否注册")
    public AbstractBean haverWxRegister(String openid,String unionId) {
        HashMap<String, Object> map = wxLoginService.haverWxRegister(openid,unionId);
        if(map != null){
            return json(map);
        }
        return null;
    }
}
